import * as vscode from "vscode";
import { join, normalize } from "path";
import { existsSync, readFileSync } from "fs";
import { TextDocumentUtils } from "../../util/document";
import { QuoteType } from "../../util/types";

export class UseModelDefinitionProvider implements vscode.DefinitionProvider {
  provideDefinition(document: vscode.TextDocument, position: vscode.Position) {
    const filePath = document.uri.fsPath;

    document.positionAt(position.character);
    const documentUtil = new TextDocumentUtils(document);
    let range = documentUtil.getQuoteRange(position, QuoteType.single);
    if (!range) {
      range = documentUtil.getQuoteRange(position, QuoteType.double);
      if (!range) {
        range = documentUtil.getQuoteRange(position, QuoteType.backtick);
      }
      if (!range) {
        return;
      }
    }
    
    const line = document.lineAt(range.start.line).text;
    if (!line.includes("useModel")) {
      return;
    }

    let workspacePath = "";
    if (vscode.workspace.workspaceFolders?.length) {
      workspacePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
      workspacePath = normalize(workspacePath);
    }

    const cwd = workspacePath;

    let ProviderPath: string = join(
      cwd,
      "src",
      ".umi",
      "plugin-model",
      "model.ts"
    );

    try {
      const ProviderFile = readFileSync(ProviderPath).toString();
      const namespace = document.getText(range);

      if (ProviderFile.indexOf(namespace) === -1) {
        return;
      }

      const numRegex = new RegExp(`from\s*(.*)${namespace}'`, "g");

      const match: any = ProviderFile.match(numRegex);
      if (!match[0]) {
        return;
      }
      const pstr:string = match[0];
      const uri:string = pstr.replace('from','').replace(/'/g,'').trim();

      let definitionFile = "";
      if (existsSync(`${uri}.ts`)) {
        definitionFile = `${uri}.ts`;
      } else if (existsSync(`${uri}.tsx`)) {
        definitionFile = `${uri}.tsx`;
      } else if (existsSync(`${uri}.js`)) {
        definitionFile = `${uri}.js`;
      } else if (existsSync(`${uri}.jsx`)) {
        definitionFile = `${uri}.jsx`;
      }
  
      if (existsSync(definitionFile)) {
        return new vscode.Location(
          vscode.Uri.file(definitionFile),
          new vscode.Position(0, 0)
        );
      }
    } catch (error) {
      console.log("===================");
      console.log(error);
      console.log("===================");
    }
  }
}
